package com.quwan.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quwan.anno.AccessCount;
import com.quwan.app.service.DispatchOrderService;
import com.quwan.app.service.PrePaymentInterface;
import com.quwan.app.vo.dispatch.*;
import com.quwan.app.vo.pay.PrePayment;
import com.quwan.common.BaseController;
import com.quwan.common.Check;
import com.quwan.common.enums.OrderScaleEnum;
import com.quwan.common.enums.PaymentEnum;
import com.quwan.common.exception.ExpCode;
import com.quwan.common.result.ApiResult;
import com.quwan.common.result.PageResult;
import com.quwan.component.ComponentFactory;
import com.quwan.config.yml.PaymentBalanceConfig;
import com.quwan.entity.TScaleSetting;
import com.quwan.entity.TSystemPay;
import com.quwan.manager.service.SystemService;
import com.quwan.mapper.TScaleSettingMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author quan
 * @date 2022-05-25 10:01
 */
@Api(tags = "App派单接口")
@RestController
@RequestMapping("app/dispatch")
@RequiredArgsConstructor
public class DispatchOrderController extends BaseController {

    private final DispatchOrderService service;
    private final SystemService systemService;
    private final ComponentFactory componentFactory;
    private final PaymentBalanceConfig balanceConfig;
    private  final TScaleSettingMapper scaleSettingMapper;


    @ApiOperation("(完成订单)派单订单")
    @PostMapping("confirm")
    public ApiResult<String> confirmOrder(HttpServletRequest request,
                                          @ApiParam("派单id") @RequestParam String id) {
        return service.confirmOrder(getId(request), id) ? ApiResult.success() : ApiResult.failed();

    }

    @ApiOperation("(取消/下架)派单订单")
    @PostMapping("cancel")
    public ApiResult<String> cancelOrder(HttpServletRequest request,
                                         @ApiParam("派单id") @RequestParam String id) {
        return service.cancelOrder(getId(request), id) ? ApiResult.success() : ApiResult.failed();

    }

    @ApiOperation("派单 订单状态详情信息")
    @PostMapping("consumeOrderInfo")
    public ApiResult<ConsumeOrderDetailInfoDTO> orderStatusInfo(HttpServletRequest request,
                                                                @ApiParam("派单id") @RequestParam String id) {

        ConsumeOrderDetailInfoDTO ret = service.orderStatusInfo(getId(request), id);
        return ApiResult.success(ret);

    }

    @ApiOperation("（派单人）申请接单用户列表数据")
    @PostMapping("chooseList")
    public ApiResult<PageResult<ApplyMemberDTO>> chooseServiceList(
            @ApiParam("派单id") @RequestParam String id,
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize) {

        PageResult<ApplyMemberDTO> ret = service.getChooseServiceList(id, pageNo, pageSize);
        return ApiResult.success(ret);

    }

    @ApiOperation("（派单人）选择接单人")
    @PostMapping("chooseService")
    public ApiResult<PrePayment> chooseServiceMember(HttpServletRequest request,
                                                     @ApiParam("派单id") @RequestParam String id,
                                                     @ApiParam("申请接单id") @RequestParam String applyId,
                                                     @ApiParam("支付方式 0余额 1wx 2zfb") @RequestParam String payType) {
        List<TSystemPay> payPowerList = systemService.getPayPowerList();
        TSystemPay pay = null;
        for (TSystemPay power : payPowerList) {
            if (power.getPayKey().equals(payType)) {
                pay = power;
                break;
            }
        }
        if (pay == null || pay.getStatus() == 0)
            return ApiResult.failed(ExpCode.PAY_NOT_SUPPORT.getMsg());

        PrePaymentInterface payInstance = componentFactory.getPayInstance(PaymentEnum.getByType(payType));

        // return service.chooseServiceMember(getId(request), id, applyId,payInstance,payType) ? ApiResult.success() : ApiResult.failed();
        return ApiResult.success(service.chooseServiceMember(getId(request), id, applyId, payInstance, payType));

    }

    @ApiOperation("（派单人）我的订单列表")
    @PostMapping("consumerOrderList")
    public ApiResult<PageResult<ConsumerDispatchOrderDTO>> consumerDispatchOrderList(HttpServletRequest request,
                                                                                     @ApiParam(" -1查询所有订单 0待处理 1进行中 2已完成 4取消") @RequestParam(defaultValue = "0") Integer type,
                                                                                     @RequestParam(defaultValue = "1") int pageNo,
                                                                                     @RequestParam(defaultValue = "10") int pageSize) {

        PageResult<ConsumerDispatchOrderDTO> ret = service.consumerDispatchOrderList(getId(request), type, pageNo, pageSize);
        return ApiResult.success(ret);

    }

    @ApiOperation("（接单人）我的订单列表")
    @PostMapping("serviceOrderList")
    public ApiResult<PageResult<ServiceDispatchOrderDTO>> serviceDispatchOrderList(HttpServletRequest request,
                                                                                   @ApiParam("-1查询所有订单 0待处理 1进行中 2已完成 4取消") @RequestParam(defaultValue = "0") Integer type,
                                                                                   @RequestParam(defaultValue = "1") int pageNo,
                                                                                   @RequestParam(defaultValue = "10") int pageSize) {

        PageResult<ServiceDispatchOrderDTO> ret = service.serviceDispatchOrderList(getId(request), type, pageNo, pageSize);
        return ApiResult.success(ret);

    }


    @ApiOperation("（接单人）申请接单")
    @PostMapping("apply")
    public ApiResult<String> apply(HttpServletRequest request,
                                   @ApiParam("派单id") @RequestParam String id,
                                   @ApiParam("日期 05-28") String date,
                                   @ApiParam("时间 12:00") String time) {
        String msg = service.checkApply(getId(request), id);
        if (msg != null)
            return ApiResult.error(msg);
        Boolean success = service.applyDispatchOrder(getId(request), id, date, time);
        return ApiResult.success();
    }


    @ApiOperation("派单信息")
    @PostMapping("detail")
    public ApiResult<DispatchOrderDTO> dispatchOrderDetail(HttpServletRequest request,
                                                           @ApiParam("派单id") @RequestParam String id) {
        String mId = getId(request);
        DispatchOrderDTO ret = service.getDispatchOrderDetail(mId, id);
        return ApiResult.success(ret);
    }

    @AccessCount
    @ApiOperation("派单列表数据")
    @PostMapping("list")
    public ApiResult<PageResult<DispatchOrderDTO>> dispatchOrderList(
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "20") int pageSize,
            @ApiParam("地区代码 对应派单cityCode") @RequestParam(required = false) String cityCode,
            @ApiParam("分类筛选 传id") @RequestParam(required = false) String categoryId,
            @ApiParam("价格排序 0正序 1倒叙") @RequestParam(required = false) String sortPrice) {
        PageResult<DispatchOrderDTO> ret = service.getDispatchOrderList(pageNo, pageSize, cityCode, categoryId, sortPrice);
        return ApiResult.success(ret);

    }


    @ApiOperation("（派单人）发起派单订单")
    @PostMapping("publish")
    public ApiResult<PrePayment> publishDispatchOrder(@Validated DispatchOrderParams params, HttpServletRequest request) {
//
//        List<String> timeList =
//                params
//                        .getTimeLimit()
//                        .stream()
//                        .filter(f -> Pattern.matches(AppConst.PUBLISH_ORDER_TIME, f))
//                        .collect(Collectors.toList());
//
//        if (CollectionUtils.isEmpty(timeList))
//            throw new ResponseException(400, "时间参数校验失败");

        String mId = getId(request);
        Check.state(StringUtils.isNotBlank(mId), ExpCode.LOGIN_TOKEN_EXPIRED);

        boolean action =  service.checkDispatchOrder(mId);
        Check.state(action,ExpCode.PUBLISH_ORDER_LIMIT);

        List<TSystemPay> payPowerList = systemService.getPayPowerList();
        TSystemPay pay = null;
        for (TSystemPay power : payPowerList) {
            if (power.getPayKey().equals(params.getPayType())) {
                pay = power;
                break;
            }
        }
        if (pay == null || pay.getStatus() == 0)
            return ApiResult.failed(ExpCode.PAY_NOT_SUPPORT.getMsg());

        PrePaymentInterface payInstance = componentFactory.getPayInstance(PaymentEnum.getByType(params.getPayType()));
        PrePayment ret = service.PrePayDispatchOrder(mId, params, payInstance);

        return ApiResult.success(ret);

    }


//    @ApiOperation("（派单人）发起派单订单")
//    @PostMapping("publish")
//    public ApiResult<String> publishOrder(@Validated DispatchOrderParams params, HttpServletRequest request) {
//
//        List<String> timeList =
//                params
//                        .getTimeLimit()
//                        .stream()
//                        .filter(f -> Pattern.matches(AppConst.PUBLISH_ORDER_TIME, f))
//                        .collect(Collectors.toList());
//
//        if (CollectionUtils.isEmpty(timeList))
//            throw new ResponseException(400, "时间参数校验失败");
//
//        String mId = getId(request);
//        Check.state(StringUtils.isNotBlank(mId), ExpCode.LOGIN_TOKEN_EXPIRED);
//        return service.publishOrder(mId, params.setTimeLimit(timeList)) ? ApiResult.success() : ApiResult.failed();
//    }

    @ApiOperation("派单定金价格计算")
    @PostMapping("compute/price")
    public ApiResult<String> computePrice(String price) {
        TScaleSetting setting = scaleSettingMapper.selectOne(new QueryWrapper<>(new TScaleSetting().setType(OrderScaleEnum.DISPATCH_ORDER_BEFORE.getType())));
        BigDecimal scale = new BigDecimal(OrderScaleEnum.DISPATCH_ORDER_BEFORE.getDefScale());
        if (setting!=null && setting.getScale().doubleValue()>0)
            scale = setting.getScale();
        return ApiResult.success((new BigDecimal(price).multiply(scale).stripTrailingZeros().toPlainString()));
    }

    @ApiOperation("派单申请订单信息")
    @PostMapping("apply/info")
    public ApiResult<ConsumeOrderDetailInfoDTO> applyOrderInfo(HttpServletRequest request,
                                                               @ApiParam("派单id") @RequestParam String id) {

        ConsumeOrderDetailInfoDTO ret = service.getApplyOrderInfo(id);
        return ApiResult.success(ret);
    }

    @ApiOperation("派单申请取消")
    @PostMapping("apply/cancel")
    public ApiResult applyOrderCancel(HttpServletRequest request,
                                      @ApiParam("派单id") @RequestParam String id) {

        String mId = getId(request);
        boolean success = service.cancelApplyOrder(mId, id);
        return service.cancelApplyOrder(mId, id) ? ApiResult.success() : ApiResult.failed();
    }
}
